package com.winai.launcher.manager;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.wifi.WifiManager;

import androidx.annotation.NonNull;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.utils.NotifyReceiverUtils;

import static android.net.NetworkInfo.State.CONNECTED;

public class NetworkManager {
    private static NetworkManager mInstance;
    private Context mContext;

    private NetworkCallbackImpl networkCallback;
    private ConnectivityManager connectivityManager;

    private WifiItemBean connectedWifi = null;//系统已连接的WiFi
    private WifiItemBean lostWifi = null;//系统断开连接的WiFi
    private WifiManager mWifiManager;

    public WifiItemBean getLostWifi() {
        return lostWifi;
    }

    public void setLostWifi(WifiItemBean lostWifi) {
        this.lostWifi = lostWifi;
    }

    public WifiItemBean getConnectedWifi() {
        return connectedWifi;
    }

    public void setConnectedWifi(WifiItemBean connectedWifi) {
        this.connectedWifi = connectedWifi;
    }

    public NetworkManager(Context context) {
        this.mContext = context;
    }

    public void init() {
        networkCallback = new NetworkCallbackImpl();
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        NetworkRequest request = builder.build();
        connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(request, networkCallback);
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    }

    public void destroy() {
        if (connectivityManager != null && networkCallback != null) {
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }
    }

    public static NetworkManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (NetworkManager.class) {
                if (null == mInstance) {
                    mInstance = new NetworkManager(context.getApplicationContext());
                }
            }
        }
        return mInstance;
    }

    /**
     * 作者：康少
     * 时间：2020/5/12 0012
     * 说明：网络监听变化实现类
     */
    public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
        /**
         * 网络可用的回调连接成功
         */
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            if (networkInfo == null) {
                return;
            }
            NetworkInfo.State state = networkInfo.getState();
            String SSID = networkInfo.getExtraInfo();
            SSID = SSID.replace("\"", "");
            LogUtils.e("onAvailable SSID = " + SSID + "，连接状态：" + state);
            if (state == CONNECTED) {
                if (connectedWifi != null) {
                    connectedWifi = null;
                }
                WifiItemBean bean = new WifiItemBean();
                bean.setWifiName(SSID);
                bean.setLinkStatus(WifiItemBean.LinkState.LINKED);
                connectedWifi = bean;
                GlobalPublisher.Notify(GlobalPublisher.NETWORK_AVAILABLE);
                NotifyReceiverUtils.notifyNetworkChanged(mContext, true);
            }
        }

        /**
         * 网络不可用时调用和onAvailable成对出现
         */
        @Override
        public void onLost(Network network) {
            super.onLost(network);
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            if (networkInfo == null) {
                return;
            }
            NetworkInfo.State state = networkInfo.getState();
            String SSID = networkInfo.getExtraInfo().replace("\"", "");
            LogUtils.e("onLost SSID = " + SSID + "，连接状态：" + state);
            if (state != CONNECTED) {
                if (lostWifi != null) {
                    lostWifi = null;
                }
                WifiItemBean bean = new WifiItemBean();
                bean.setWifiName(SSID);
                bean.setLinkStatus(WifiAutoConnectManager.newInstance(mWifiManager)
                        .isExsits(SSID) != null
                        ? WifiItemBean.LinkState.SAVED : WifiItemBean.LinkState.UNLINK);
                lostWifi = bean;
                connectedWifi = null;
                GlobalPublisher.Notify(GlobalPublisher.NETWORK_LOST);
                NotifyReceiverUtils.notifyNetworkChanged(mContext, false);
            }
        }

        /**
         * 实践中在网络连接正常的情况下，丢失数据会有回调
         */
        @Override
        public void onLosing(Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
            LogUtils.e("onLosing");
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            LogUtils.e("onUnavailable");
        }

        @Override
        public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            LogUtils.e("onCapabilitiesChanged：networkCapabilities = " + networkCapabilities.toString());
        }

        @Override
        public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties);
            LogUtils.e("onLinkPropertiesChanged：linkProperties = " + linkProperties.toString());
        }

        @Override
        public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {
            super.onBlockedStatusChanged(network, blocked);
            LogUtils.e("onBlockedStatusChanged：blocked = " + blocked);
        }
    }
}
